<?php
declare(strict_types=1);

namespace open\controller;

use open\comm\traits\OpenVerifyTrait;
use support\Request;


/**
 * 开放接口基类
 * Class OpenApi
 * @package open\controller
 * @author ycr <Email: yuncran@126.com>
 */
abstract class OpenApi
{

    use OpenVerifyTrait;


    protected $url = ['/v1/open'];


    /**
     * @param Request $request
     * @return bool
     * @author ycr <Email: yuncran@126.com>
     */
    public function beforeAction(Request $request)
    {
        try {
            // 1、速率控制
            // 2、去验证app_id app-secret
            // 3、验证数据合法性
            // 4、加入队列中转释放接口请求
            if (in_array($request->route->getPath(), $this->url)) {
                $http_response = $this->before($request);  # 去验证app_id app-secret
                $this->createJwt($http_response);
                return true;
            }
            // 验证数据合法性
            $token = $request->post('token');
            if (empty($token)) {
                return app('json')->fail('缺少Token');
            }
            if (!$this->OpenVerifyToken($token)) {
                return app('json')->fail('token 验证失败！');
            }
            // 加入队列中转释放接口请求
            $data_push = ['url' => serialize($request->uri())];
            Yii()->redis::lPush('open_url', json_encode($data_push));


        } catch (\Throwable $exception) {
            var_export(['a' => $exception->getMessage(), 'b' => $exception->getLine(), 'c' => $exception->getFile()]);
            return app('json')->fail($exception->getMessage());
        }


    }

    /**
     * 暂时未想好处理什么东西
     * 该方法会在请求后调用
     * @param Request $request
     * @author ycr <Email: yuncran@126.com>
     */
    public function afterAction(Request $request)
    {
//        echo 'afterAction';
        // 如果想串改请求结果，可以直接返回一个新的Response对象
        // return response('afterAction');
    }

}